import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import PreviewImage from "@/utils/preview-image";
import PreviewVideo from "@/utils/preview-video";
import PreviewDocument from '@/utils/preview-document';
import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'
// iconfont
import './assets/iconfont/iconfont.css'

import '@/icons' // icon
import '@/permission' // permission control

import './css/theme.scss'
import pApi from "@/api/permissionApi";

// 自定义指令（input输入数字  小数点两位）
import { inputLimt } from './utils/inputLimt'
Vue.directive('inputLimit', inputLimt)


// 秒数转时分秒
import { generateDetail, } from '@/utils/projectExcel';
Vue.prototype.$generateDetail = generateDetail;
// 文件判断显示预览图
import { filePostImgFunc } from './utils/auth';
Vue.prototype.$filePostImgFunc = filePostImgFunc;
// 获取视频文件流封面图
import { videoPost, videoPostOnline, isVideoFile, fileImgFunc, dateTimeToDate, msgJump } from './utils/auth';
Vue.prototype.$videoPost = videoPost;//返回文件封面图
Vue.prototype.$videoPostOnline = videoPostOnline;//返回文件封面图
Vue.prototype.$isVideoFile = isVideoFile;//是否视频
Vue.prototype.$fileImgFunc = fileImgFunc;
Vue.prototype.$dateTimeToDate = dateTimeToDate;
// 消息跳转
Vue.prototype.$msgJump = msgJump
// 打开导出数据模板
Vue.prototype.$openUrlFunc = (url) => {
  // window.open(url, '_blank')
  const xhr = new XMLHttpRequest()
  xhr.open('GET', url + '?v=' + Date.now(), true)
  xhr.responseType = 'blob'
  xhr.onload = () => {
    const data = window.URL.createObjectURL(xhr.response)
    // 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = url.split('/').pop();
    eleLink.style.display = 'none';
    // 下载内容转变成blob地址
    eleLink.href = data;
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
  }
  xhr.send()
}

// 判断字段显示
Vue.prototype.$fieldShowFunc = (field) => {
  let fieldList = store.getters.fieldList.checkedList;
  // return fieldList[field] == undefined ? true : fieldList[field];
  return fieldList.includes(field)
}
// 求余详情列数
Vue.prototype.$fieldRowFunc = (idx, idx2, idx3, fields = []) => {
  let fieldList = store.getters.fieldList.field_data;
  let noField = [
    'kh_tx', //客户详情
    'sh_shclf', 'sh_shrgf', 'sh_shdhrq', 'sh_shdhrq2', 'sh_shcgzy', 'sh_shwldh', //售后详情
    'ys_jczxf', 'ys_zccgf', 'ys_sj', 'ys_xccgcb', 'ys_gscjcb', 'ys_glcb', //预算详情
    'js_qyje', 'js_zxjze', 'js_xccgcb', 'js_gscjcb', 'js_glcb', //结算详情
    'zjx_zjxbh', 'zjx_jczxf', 'zjx_zccgf', 'zjx_sj', 'zjx_xccgcb', 'zjx_gscjcb', 'zjx_glcb', //增减项详情
  ]
  noField = noField.concat(fields)
  let count = 0
  fieldList[idx].children[idx2].children[idx3].field_list.map(item => {
    // 过滤不要的
    if (!noField.includes(item.field_name)) {
      if (item.state) {
        count += 1
      }
    }
  })
  let y = count % 3
  console.log(fieldList[idx].children[idx2].children[idx3].field_list)
  if (y == 0) {
    return 0
  } else {
    return 3 - y
  }
}

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
// if (process.env.NODE_ENV === 'production') {
//   const { mockXHR } = require('../mock')
//   mockXHR()
// }
// 文件预览
Vue.prototype.$fileViewHandle = (file) => {
  let videoRegex = /(\mp4|\avi|\mkv|\m4v)$/i
  let imgRegex = /(\jpg|\jpeg|\png|\gif|\webp)$/i;

  if (imgRegex.test(file.file_suffix)) {
    // 图片预览
    Vue.prototype.$openPreviewImage(file.file_url);
  } else if (videoRegex.test(file.file_suffix)) {
    // 视频预览
    Vue.prototype.$openPreviewVideo(file.file_url);
  } else {
    switch (file.file_suffix) {
      // 文档预览
      case 'doc':
      case 'docx':
      case 'xls':
      case 'xlsx':
      case 'ppt':
      case 'pptx':
      case 'pdf':
        Vue.prototype.$openPreviewDocument(file);
        break;
      default:
        // 下载文件
        const xhr = new XMLHttpRequest()
        xhr.open('GET', file.file_url + '?v=' + Date.now(), true)
        xhr.responseType = 'blob'
        xhr.onload = () => {
          const data = window.URL.createObjectURL(xhr.response)
          // 创建隐藏的可下载链接
          var eleLink = document.createElement('a');
          eleLink.download = file.file_name;
          eleLink.style.display = 'none';
          // 下载内容转变成blob地址
          eleLink.href = data;
          // 触发点击
          document.body.appendChild(eleLink);
          eleLink.click();
          // 然后移除
          document.body.removeChild(eleLink);
        }
        xhr.send()

    }
  }
};

// 获取页面操作权限
Vue.prototype.$getHtmlAuthority = (path) => {
  return new Promise((resolve, reject) => {
    pApi.getHtmlAuthority({
      path,
    }).then((res) => {
      if (res.code == 200) {
        resolve(res);
      }
    });
  })
};



// 操作权限判断
Vue.prototype.$isPer = (arr, valArr) => {
  if (arr.length == 0) {
    return false;
  }
  if (valArr.length == 1) {
    return arr.includes(valArr[0]);
  }
  let res = [];
  valArr.map(item => {
    if (arr.includes(item)) {
      res.push(true);
    }
  })
  return res.length != 0;
};

// 返回上一页（并删除顶部tab）
Vue.prototype.$goBackTab = (that, cb) => {
  let router = that.$router
  let path = that.$route.path
  let store = that.$store
  store.commit('isEventTriggeredFunc', true);
  let pathVal = JSON.parse(JSON.stringify(path));
  console.log(pathVal, "当前要关闭的页面")
  setTimeout(() => {
    // history.replaceState(null, '', window.location.href);//从浏览器历史记录删除
    if (cb) {
      cb();
    } else {
      router.go(-1);
    }
    Vue.nextTick(() => {
      if (store.getters.visitedViews.length != 0) {
        let index = store.getters.visitedViews.findIndex((item) => {
          return item.path == pathVal;
        });
        store.dispatch("tagsView/delView", store.getters.visitedViews[index]).then((res) => {
          console.log(res, "删除页面tab");
        });
      }
    });
  }, 200)
}

// 组装列表编号
Vue.prototype.$assemblyListNo = (text, num) => {
  // 将数字转换为字符串
  const numStr = String(num);
  if (numStr.length > 5) {
    return text + numStr;
  }
  // 使用 padStart 方法在前面补零，直到字符串长度为 5
  return text + numStr.padStart(5, '0');
}

Vue.use(PreviewImage);
Vue.use(PreviewVideo);
Vue.use(PreviewDocument);
Vue.use(ElementUI, { zhLocale })

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
